package com.springboot.framework.jwt;

import com.auth0.jwt.exceptions.JWTDecodeException;
import com.springboot.framework.exception.BaseException;
import org.springframework.web.method.HandlerMethod;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 通用token拦截器的一些通用处理
 */
public abstract class TokenInterceptor {

    /**
     * 返回true就放行到控制层
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler,TokenServiceResolver resolver) throws Exception {
        //从 http 请求头中取出 token
        String token = request.getHeader("token");
        // 如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        HandlerMethod handlerMethod=(HandlerMethod)handler;
        Method method = handlerMethod.getMethod();
        //检查是否有passToken注解，有则跳过认证
        if (method.isAnnotationPresent(PassToken.class)) {
            PassToken passToken = method.getAnnotation(PassToken.class);
            if (passToken.required()) {
                return true;
            }
        }
        // 执行认证
        if (token == null) {
            throw new BaseException("无token，请重新登录");
        }
        // 解析token,获取 token 中的 用户标识
        String userMark;
        try {
            userMark = JWTUtil.decryptToken(token);
        } catch (JWTDecodeException j) {
            throw new BaseException("401");
        }
        boolean isPass = resolver.doService(userMark);
        return isPass;
    }

}
